package com.guiwu.gteway.industryapp.Api.http;

import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Headers;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;

public class HttpExecutor {

    private OkHttpClient mOkhttpClient;

    //头部数据
    public static final String USER_ID = "userId";
    public static final String GATEWAY_SN = "sn";
    public static final String CAMERA_SERIAL = "deviceSerial";
    public static final String API_KEY = "api-key";
    public static final String CONTENT_TYPE = "Content-Type";

    public HttpExecutor(OkHttpClient okHttpClient){
        mOkhttpClient = okHttpClient;
    }

    //多个请求头
    public void get(String url, Callback callback, Map<String,String> headsMap){
        Headers.Builder hdBuilder = new Headers.Builder();
        for (String key:headsMap.keySet()){
            hdBuilder.add(key,headsMap.get(key));
        }
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.headers(hdBuilder.build());
        requestBuilder.get();
        execute(requestBuilder.build(),callback);
    }

    //单个请求头
    public void get(String url,Callback callback,String headType ,String head){
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.header(headType,head);
        execute(requestBuilder.build(),callback);
    }


    public void post(String url, RequestBody requestBody, Callback callback , String headType, String head) {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        if (head != null)
            requestBuilder.addHeader(headType,head);
        requestBuilder.post(requestBody);
        execute(requestBuilder.build(), callback);
    }

    public void put(String url, RequestBody requestBody, Callback callback) {
        Request.Builder requestBuilder = new Request.Builder().url(url);
        requestBuilder.put(requestBody);
        execute(requestBuilder.build(), callback);
    }

    private void execute(Request request,Callback callback){
        Call call = mOkhttpClient.newCall(request);
        call.enqueue(callback);
    }
}
